<script lang="ts" setup>
import { storeToRefs } from 'pinia';
import { ref } from 'vue';
import { usePopupStore } from '@/store/popup';
import { Coupon } from '@/types/coupon';
import { useLocale } from '@/locale/locale';

const { t } = useLocale();
const popupStore = usePopupStore();
const { couponPickerRef } = storeToRefs(popupStore);

const props = withDefaults(
  defineProps<{
    selected: number;
    items: Coupon[];
    confirmColor: string;
    from: string;
  }>(),
  {
    confirmColor: '#269c74',
    from: 'hotel'
  }
);

const emit = defineEmits(['update']);
const current = ref<number>();

popupStore.onOpened('COUPON', () => {
  current.value = props.selected;
});

function handleConfirm() {
  popupStore.closeCouponPicker();
  emit('update', current.value);
}

function handleSelect(id: number) {
  current.value = current.value === id ? 0 : id;
}
</script>

<template>
  <apt-popup
    ref="couponPickerRef"
    :title="t('LRKey_coupon')"
    :confirm-btn-color="confirmColor"
    @close="popupStore.closeCouponPicker"
    @confirm="handleConfirm"
  >
    <scroll-view scroll-y style="height: 40vh">
      <view v-for="item in items" :key="item.id">
        <apt-coupon
          :id="item.id"
          :at-least="item.atLeast"
          :can-use="item.use"
          :description="item.desc"
          :end-date="item.endTime"
          :properties="item.propertyNames"
          :scene="item.scene"
          :start-date="item.startTime"
          :status="item.state"
          :title="item.couponName"
          :from="from"
          @select="handleSelect"
        >
          <template v-if="item.state === 1 && item.use">
            <image
              v-if="current === item.id"
              class="w-5 h-5"
              src="/static/icon_coupon_checked.png"
            />
            <image v-else class="w-5 h-5" src="/static/icon_coupon_unchecked.png" />
          </template>
        </apt-coupon>
      </view>
    </scroll-view>
  </apt-popup>
</template>
